####################################################
# Copyright (c) 2002-2007 BioWare Corp.
# http://www.bigdaddymonitor.org
#
# This file is part of the BigDaddy Monitoring
# program. It is free software distributed under
# the terms of the BSD License. It is ditributed
# in the hopes that it will be useful, but
# WITHOUT ANY WARRANTY; without event the implied
# warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
#
# The BSD License is available from:
# http://www.opensource.org/licenses/bsd-license.php
####################################################

package      BioMain;
require      Exporter;

use          DBI;
use          strict;
use          Config::IniFiles;
use          LWP::Simple;

our @ISA            = qw(Exporter);
# Symbols to be exported by request
our @EXPORT_OK      = qw(callfor_db_handle get_dbinfo check_logfile logEntry cronstart cronend cronlog);
# Export as group
our %EXPORT_TAGS = (
                     logfunctions => [qw(check_logfile logEntry)],
                     allfunctions => [qw(callfor_db_handle check_logfile logEntry cronstart cronend get_dbinfo cronlog)],
                     cronfunctions => [qw(cronstart cronend cronlog)],
                   );
# Version number
our $VERSION        = 1.01;
################################################################
# BioMain Module
# BioWare Corp, 2003


=head1 BioMain

Contains the main functions for perl scripts around the BioNix systems.

=head2 Description

#Exportable functions:

=item use BioMain qw(callfor_db_handle biomail check_logfile logEntry cronstart cronend);

=item use BioMain qw(:allfunctions);

=item use BioMain qw(:logfunctions);
#All Log Functions check_logfile and logEntry


=item use BioMain qw(:cronfunctions);
#Only Cron Start and Cron End functions


=head2 callfor_db_handle(str Database, int RaiseError, int TimeOutSetting)

Provides the database handle for a database ini file.
Raise Error indicates whether the connection should give errors (0 for no, 1 for yes)
and the timeoutsetting of 99 will prevent the connection from timing out and closing.

example:

callfor_db_handle("mailsystem", 0, 99);

=head2 check_logfile(str logFileName, str logHeaderString)

Checks for the existence of a log file at path logFileName, creates the file and
sets the log header and start of the script logging using logHeaderString


example:

check_logfile("/www/perl/logs/test.log", "Test Log Log");


=head2 logEntry(str logEntry, str logFileName, int Action)

Adds the log entry (logEntry) into the file logFileName. The int Action (0 or 1) will
either exit the script after putting the entry into the log.

logEntry("File Does Not Exist", "/www/perl/logs/test.log", 1);

=head2 cronstart(int cronID)

Do this at the start of any cron job to connect it to the BigDaddy CronTab Control
ID must correspond with the correct cronID in BigDaddy

=head2 cronend(int cronID)

Do this at the end of any cron job. If you don't do this and you do cronstart, remember
that monitoring may kick in!


=head2 Author

Duleepa Wijayawardhana
dups@bioware.com // 04.02.2004
(c) 2004 BioWare Corp.

=cut

my $dbconfig_ini="/bigdaddy/bigdaddy_dbconfig.ini";
my $bd_ini = "/bigdaddy/bigdaddy.ini";
my $dbh;
my %CronStartVars;

sub get_handle
{
	my ($db_name, $db_host, $db_user, $db_passwd, $raiseError, $timeout) = @_;

	my $host_string="DBI:mysql:database=".$db_name.";host=".$db_host;
	$dbh=DBI->connect($host_string, $db_user, $db_passwd, { RaiseError => $raiseError, AutoCommit => 1 });

	#if the timeout is set to 99 then we want to make this connection immune
	#to idle crashing

	if ( $timeout==99 && defined($dbh) )
	{
		my $sql="SET wait_timeout=28800";
		$dbh->do($sql);
	}

	return $dbh;
}


#===================================================================================================
# Calls the get_handle subroutine
# Dups
#===================================================================================================

sub callfor_db_handle
{
	my ( $DBSection, $raiseError, $timeOutSetting ) = @_;

	if ( $raiseError!=1 && $raiseError!=0 )
	{
		$raiseError=1;
	}


	my $cfg = Config::IniFiles->new( -file => $dbconfig_ini );

	my $DBName;

	my $DBHost=$cfg->val( $DBSection, 'host' );
	my $DBUser=$cfg->val( $DBSection, 'user' );
	my $DBPass=$cfg->val( $DBSection, 'pass' );

	if ( $cfg->val( $DBSection, 'database' ) ne '' )
	{
		$DBName=$cfg->val( $DBSection, 'database' );
	}
	else
	{
		$DBName=$DBSection;
	}

	$dbh=get_handle( $DBName, $DBHost, $DBUser, $DBPass, $raiseError, $timeOutSetting );
	return $dbh;
}

#===================================================================================================
# Gets info on a database
# Dups 23.03.2004
#===================================================================================================

sub get_dbinfo
{
	my ( $DBSection ) = @_;

	my $cfg = Config::IniFiles->new( -file => $dbconfig_ini );

        my %DBInfo;

	$DBInfo{'host'}=$cfg->val( $DBSection, 'host' );
	$DBInfo{'user'}=$cfg->val( $DBSection, 'user' );
	$DBInfo{'pass'}=$cfg->val( $DBSection, 'pass' );

	if ( $cfg->val( $DBSection, 'database' ) ne '' )
	{
		$DBInfo{'database'}=$cfg->val( $DBSection, 'database' );
	}
	else
	{
		$DBInfo{'database'}=$DBSection;
	}

	return %DBInfo;
}

################################################################
#Check Log file

sub check_logfile
{
	my ($logfilename, $logfileStr)=@_;

	if ($logfilename ne '')
	{
		my ($seconds, $minutes, $hours, $day, $month, $year, $wday, $yday, $isdst)=localtime();
		open (LOGFILE, ">> $logfilename")
			or die "Could not open $logfilename for writing: $!\n";
		print LOGFILE $logfileStr." Started: ".log_addzero($day)."/".log_addzero($month+1)."/".($year+1900)." ".log_addzero($hours).":".log_addzero($minutes).":".log_addzero($seconds)."\n";
		close (LOGFILE)
			or die "Could not close $logfilename: $!\n";
	}

}

################################################################
#Log Entry Create
#action=1 => die (terminate)

sub logEntry
{
	my ($logEntryStr, $logfilename, $action)=@_;
	my ($seconds, $minutes, $hours, $day, $month, $year, $wday, $yday, $isdst)=localtime();

	$logEntryStr="[".log_addzero($day)."/".log_addzero($month+1)."/".($year+1900)." ".log_addzero($hours).":".log_addzero($minutes).":".log_addzero($seconds)."] ".$logEntryStr;

	if ($action==1)
	{
		$logEntryStr.=": Terminating";
	}

	$logEntryStr.="\n";

	#Open the log file and write the string
	open (LOGFILE, ">> $logfilename")
		or die "Could not open $logfilename for writing: $!\n";
	print LOGFILE $logEntryStr;
	close (LOGFILE)
		or die "Could not close $logfilename: $!\n";

	if ($action==1)
	{
		exit;
	}
}

#################################################################
# Add Zero Log

sub log_addzero
{
	my ($number) = @_;
	if ($number<10)
	{
		return "0".$number;
	}
	else
	{
		return $number;
	}

}

#################################################################
# Run this at the start of a cron
sub cronstart
{
    my ($cronID) = @_;
	
	my $bdcfg = Config::IniFiles->new( -file => $bd_ini );
    my $url = $bdcfg->val('main', 'url');
    
    $url = $url."?page=SetCronStart&cronID=".$cronID;
    my $content = get $url;
    die "Couldn't get $url" unless defined $content;
    
    if ($content =~ m/fail/i)
    {
        die ("Cron is disabled or delayed");
    }
    elsif ($content =~ m/success/i)
    {
        
    }
    else
    {
        die("Unknown Error perhaps");
    }

}
#################################################################
# Run this at the END of a cron
sub cronend
{
    my ($cronID) = @_;
	
	my $bdcfg = Config::IniFiles->new( -file => $bd_ini );
    my $url = $bdcfg->val('main', 'url');
    
    $url = $url."?page=SetCronEnd&cronID=".$cronID;
    my $content = get $url;
    die "Couldn't get $url" unless defined $content;
}

#################################################################
# Run this to log an entry into the cron
sub cronlog
{
    my ($cronID, $text) = @_;
    
    my $bdcfg = Config::IniFiles->new( -file => $bd_ini );
    my $url = $bdcfg->val('main', 'url');
        
    $url = $url."?page=SetCronLog&cronID=".$cronID."&log=".$text;
    my $content = get $url;
    die "Couldn't get $url" unless defined $content;
}



1;
